<template>
  <div class="newNotice">
    <div class="newNoticeM">
      <el-form ref="form" :model="form" :label-position="labelPosition" label-width="120px">
        <el-form-item label="通知标题" class="sure">
          <el-input v-model="form.title" style="width:500px;"></el-input>
          <em
            v-show="error"
            style="display: block;line-height: 17px;margin-top: 10px;color: red;"
          >通知标题不得超过100个字！</em>
        </el-form-item>
        <el-form-item label="通知类型" class="sure">
          <el-select v-model="form.typeId" placeholder="请选通知类型">
            <el-option v-for="(item,index) in messageTypeList" :key="index" :label="item.typeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件重要性" class="sure">
          <el-select v-model="form.noticeImportance" placeholder="请选择文件重要性">
            <el-option label="一般" value="1"></el-option>
            <el-option label="重要" value="2"></el-option>
            <el-option label="紧急" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接收人员" class="sure">
          <div class="peoList">
            <span v-for="(m) in right.list" :key="m.userId">
              {{m.userName}}
              <em @click="right_delete(m.userId)">删除</em>
            </span>
            <a class="choPeo" @click="openLayer">
              <i class="icon iconfont iconrenyuanzengjia"></i>
            </a>
          </div>
        </el-form-item>
        <el-form-item label="通知正文">
          <quill-editor
            v-model="form.content"
            class="textearMesBox"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="上传附件">
          <div class="fileBox">
            <div class="inputBox">
              <input type="file" name="file" id="file" multiple @change="fileCho($event)">
              <i class="el-icon-upload"></i> 上传附件
            </div>
            <ul>
              <li v-for="(fl,index) in filesList" v-bind:key="index">
                <a>{{fl.name}}</a>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeUpImg(index)"
                ></el-button>
              </li>
            </ul>
          </div>
        </el-form-item>
      </el-form>
      <div class="clear"></div>

      <div class="bts">
        <el-button type="primary" @click="xinjian" :loading="submitflag">发 布</el-button>
        <el-button @click="backPage">取 消</el-button>
      </div>
    </div>

    <el-dialog
      title="选择接收人员"
      :visible.sync="dialogVisible"
      width="800px"
      :before-close="handleClose"
      :modal-append-to-body="false"
    >
      <div style="margin-left: 5px;float:left;margin-right:20px">
        <el-radio-group v-model="transType" size="small" @change="changeTransType">
          <el-radio-button label="1">所有人员</el-radio-button>
          <el-radio-button label="2">自定义组</el-radio-button>
        </el-radio-group>
      </div>
      <div style="padding-top: 4px;">
        <el-link icon="el-icon-edit" @click="jumpToCustom">管理自定义组</el-link>
        <i
          class="el-icon-refresh"
          @click="refresh"
          title="刷新自定义组"
          style="font-size: 16px;color: #409eff;cursor:pointer"
        ></i>
      </div>
      <div style="clear:both;"></div>
      <div class="transferBox">
        <div class="transfer">
          <div class="transfer-box transfer-left">
            <h3 class="transfer-title">
              <el-checkbox
                style="margin-right:0px"
                v-model="left.checkedAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
              ></el-checkbox>
              <span>{{ left.title }}</span>
              <el-select
                v-if="transType == '1'"
                v-model="selectbox.value"
                size="mini"
                style="float: right;margin-right: 20px;width: 170px;"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in selectbox.list"
                  :label="item.unitName"
                  :value="item.unitId"
                  :key="item.unitId"
                ></el-option>
              </el-select>
              <el-select
                v-else
                v-model="selectbox.value"
                size="mini"
                style="float: right;margin-right: 20px;width: 170px;"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in selectbox.list"
                  :label="item.groupName"
                  :value="item.groupId"
                  :key="item.groupId"
                ></el-option>
              </el-select>
            </h3>
            <div class="transfer-main">
              <!-- <slot name="from"></slot> -->
              <el-input
                v-model="left.search"
                clearable
                placeholder="请输入姓名/部门搜索"
                prefix-icon="el-icon-search"
                size="small"
                class="filter-input"
              ></el-input>
              <ul>
                <li v-for="(item,index) in searchDataLeft" :key="index">
                  <el-checkbox
                    v-model="item.checked"
                    @change="left_change_one(item,item.userId,item.checked)"
                  >{{item.userName}} ({{item.unitName}} - {{item.deptName}})</el-checkbox>
                </li>
              </ul>
            </div>
          </div>
          <div class="toRight">
            <i class="el-icon-arrow-right"></i>
          </div>
          <div class="transfer-box transfer-right">
            <h3 class="transfer-title">
              <span>{{ right.title }}</span>
              <span
                style="float:right;margin-right:20px;color:#6c6c6c;font-size:12px;cursor:pointer"
                @click="deleteAll()"
              >
                <i class="el-icon-delete"></i> 清空
              </span>
            </h3>
            <div class="transfer-main">
              <!-- <slot name="from"></slot> -->
              <el-input
                v-model="right.search"
                clearable
                placeholder="请输入关键字搜索"
                prefix-icon="el-icon-search"
                size="small"
                class="filter-input"
              ></el-input>
              <ul>
                <li v-for="(item,index) in searchData" :key="index">
                  <p class="ellipsis">{{item.userName}} ({{item.unitName}} - {{item.deptName}})</p>
                  <a
                    class="deleteicon"
                    href="javascript:void(0)"
                    @click="right_delete(item.userId)"
                  >
                    <i class="el-icon-delete"></i>
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  name: "newNotice",
  components: {
    quillEditor
  },
  data() {
    return {
      submitflag: false,
      content: "cacacaca",
      error: false,
      messageTypeList: [],
      editorOption: {
        placeholder: "请输入文本..."
      },
      labelPosition: "right",
      dialogVisible: false,
      form: {
        title: "",
        typeId: "",
        noticeImportance: "",
        noticeUsers: [],
        content: ""
      },
      filesList: [],
      //********0002穿梭框开始***************
      jumpLink: "",
      isIndeterminate: false,
      transType: "1",
      selectbox: {
        //筛选框
        value: "",
        list: []
      },
      left: {
        //全部人员
        checkedAll: false,
        title: "所有人员",
        search: "",
        list: []
      },
      right: {
        //选中的人员
        checkedAll: false,
        title: "选中人员",
        search: "",
        list: [],
        selectIds: []
      }
      //*******0002穿梭框结束************
    };
  },
  //   ******0003穿梭框开始************
  computed: {
    //左侧过滤器
    searchDataLeft: function() {
      var search = this.left.search;
      if (search) {
        return this.left.list.filter(function(llist) {
          return Object.keys(llist).some(function(key) {
            if (key == "userName" || key == "deptName" || key == "unitName") {
              return (
                String(llist[key])
                  .toLowerCase()
                  .indexOf(search) > -1
              );
            }
          });
        });
      }
      return this.left.list;
    },
    //右侧过滤器
    searchData: function() {
      var search = this.right.search;
      if (search) {
        return this.right.list.filter(function(rlist) {
          return Object.keys(rlist).some(function(key) {
            if (key == "userName" || key == "deptName" || key == "unitName") {
              return (
                String(rlist[key])
                  .toLowerCase()
                  .indexOf(search) > -1
              );
            }
          });
        });
      }

      return this.right.list;
    }
  },
  watch: {
    "form.title": function(n, o) {
      if (n.length >= 101) {
        this.error = true;
      } else {
        this.error = false;
      }
    },
    "selectbox.value": function(n, o) {
      //监听下拉筛选
      if (n != o && n != "") {
        this.load_list(); //获取所有人员列表
      }
    },
    searchDataLeft: function(n, o) {
      if (n != o && n != "") {
        this.controlCheckAll();
      }
    }
  },
  //   ******0003穿梭框结束************
  mounted() {
    this.getMessageTypeList(); //获取通知类型列表
    this.getJumpLink(); //获取机构
  },
  methods: {
    getMessageTypeList() {
      let url = "/base/load/type/list";
      this.$ajax
        .post(url)
        .then(out => {
          this.hw_result(out.data, true, this, () => {
            this.messageTypeList = out.data.result;
          });
        })
        .catch(error => {});
    },
    //   **********0004穿梭框开始***************
    getJumpLink() {
      let url = "/base/query/group/url";
      this.$ajax
        .post(url)
        .then(out => {
          this.hw_result(out.data, true, this, () => {
            this.jumpLink = out.data.result;
          });
        })
        .catch(error => {});
    },
    refresh() {
      //刷新
      this.getInfo();
    },
    jumpToCustom() {
      window.open(this.jumpLink, "_blank");
    },
    changeTransType() {
      //切换tab
      this.getInfo();
    },
    getInfo() {
      //0001.获取 筛选框列表(有编辑时 选中人列表，选中人id列表，)
      this.selectbox.value = "";
      if (this.transType == "1") {
        //所有人员
        this.left.title = "所有人员";
        let url = "/base/query/units";
        this.$ajax
          .post(url)
          .then(out => {
            this.hw_result(out.data, true, this, () => {
              this.selectbox.list = out.data.result;
              this.left.list = [];
              // 默认选中第一项
              this.selectbox.value = out.data.result[0].unitId;
            });
          })
          .catch(error => {});
      } else {
        //自定义组
        this.left.title = "自定义组";
        let url = "/base/query/group/list";
        this.$ajax
          .post(url)
          .then(out => {
            this.hw_result(out.data, true, this, () => {
              this.selectbox.list = out.data.result;
              this.left.list = [];
              // 默认选中第一项
              this.selectbox.value = out.data.result[0].groupId;
            });
          })
          .catch(error => {});
      }
    },
    load_list() {
      if (this.transType == "1") {
        let unitType = "";
        for (let i = 0; i < this.selectbox.list.length; i++) {
          if (this.selectbox.value == this.selectbox.list[i].unitId) {
            unitType = this.selectbox.list[i].unitType;
          }
        }
        //0002.获取所有人员列表
        let url = "/base/query/users";
        let param = {
          unitId: this.selectbox.value,
          unitType: unitType
        };
        this.$ajax
          .post(url, param)
          .then(out => {
            this.hw_result(out.data, true, this, () => {
              let data = out.data.result;
              this.init_left(data); //初始化左侧所有人列表
            });
          })
          .catch(error => {});
      } else {
        //0002.获取所有人员列表
        let url = "/base/query/group/users";
        let param = {
          groupId: this.selectbox.value
        };
        this.$ajax
          .post(url, param)
          .then(out => {
            this.hw_result(out.data, true, this, () => {
              let data = out.data.result;
              this.init_left(data); //初始化左侧所有人列表
            });
          })
          .catch(error => {});
      }
    },
    init_left(leftList) {
      //0003初始化左侧所有人列表
      var arr = new Array();
      for (let i in leftList) {
        let s = leftList[i];
        if (this.right.selectIds.indexOf(s.userId) > -1) {
          s.checked = true;
        } else {
          s.checked = false;
        }
        arr.push(s);
      }
      this.left.list = arr;

      this.controlCheckAll();
    },
    controlCheckAll() {
      //0007控制全选按钮选中状态
      var checkedLength = 0;
      for (var i = 0; i < this.searchDataLeft.length; i++) {
        if (this.searchDataLeft[i].checked == true) {
          checkedLength++;
        }
      }
      if (checkedLength == this.searchDataLeft.length) {
        this.left.checkedAll = true;
      } else {
        this.left.checkedAll = false;
      }
    },
    left_change_one(item, id, checked) {
      this.controlCheckAll();
      //0004左边选择和不选择
      if (checked == false) {
        //取消选中时
        for (let i in this.right.list) {
          let u = this.right.list[i];
          if (u.userId == id) {
            this.right.list.splice(i, 1);
            this.right.selectIds.splice(i, 1);
          }
        }
      } else {
        this.right.list.push(item);
        this.right.selectIds.push(id);
      }
    },
    right_delete(id) {
      //0005右边删除时
      for (let i in this.right.list) {
        let u = this.right.list[i];
        if (u.userId == id) {
          this.right.list.splice(i, 1);
          this.right.selectIds.splice(i, 1);
        }
      }
      for (let i in this.left.list) {
        let u = this.left.list[i];
        if (u.userId == id) {
          u.checked = false;
        }
      }
      this.controlCheckAll();
    },
    deleteAll() {
      //0008右边清空时
      this.hw_confirm("您确定要清空吗？", () => {
        this.right.list = [];
        this.right.selectIds = [];
        for (let i in this.left.list) {
          let u = this.left.list[i];
          u.checked = false;
        }
        this.controlCheckAll();
      });
    },
    handleCheckAllChange(val) {
      //0006左边全选全不选时
      //1全选全不选
      for (let i in this.searchDataLeft) {
        let s = this.searchDataLeft[i];
        s.checked = val;
      }
      if (val == true) {
        //2全选时 去重push进去(获取左边数组在右边中没有的项)
        var arr = [];
        for (var i = 0; i < this.searchDataLeft.length; i++) {
          var obj = this.searchDataLeft[i];
          var leftid = obj.userId;
          var isExist = false;
          for (var j = 0; j < this.right.list.length; j++) {
            var obj2 = this.right.list[j];
            var rightid = obj2.userId;
            if (leftid == rightid) {
              isExist = true;
              break;
            }
          }
          if (!isExist) {
            arr.push(obj);
          }
        }
        this.right.list = this.right.list.concat(arr);
        for (var i = 0; i < arr.length; i++) {
          this.right.selectIds.push(arr[i].userId);
        }
      } else {
        //全不选时(取出右边数组中在左边数组存在的项)

        let formArr = [];
        for (let i = 0; i < this.right.list.length; i++) {
          var rightid = this.right.list[i].userId;
          var isExist = false;
          for (let j = 0; j < this.searchDataLeft.length; j++) {
            if (rightid == this.searchDataLeft[j].userId) {
              isExist = true;
            }
          }
          if (isExist == false) {
            formArr.push(this.right.list[i]);
          }
        }
        this.right.list = formArr;
        var arr2 = [];
        for (var i = 0; i < formArr.length; i++) {
          arr2.push(formArr[i].userId);
        }
        this.right.selectIds = arr2;
      }
    },
    openLayer() {
      //打开弹窗
      this.dialogVisible = true;
      this.getInfo();
    },
    handleClose(done) {
      //点击关闭弹窗时
      this.dialogVisible = false;
      //   this.$confirm("确认关闭？")
      //     .then(_ => {
      //       this.dialogVisible = false;
      //     })
      //     .catch(_ => {});
    },
    // //   **********0004穿梭框结束***************

    // 富文本编辑器开始
    onEditorBlur(quill) {},
    onEditorFocus(quill) {},
    onEditorChange(quill) {},
    // 富文本编辑器结束

    // 上传附件开始
    fileCho(event) {
      for (let i = 0; i < event.target.files.length; i++) {
        this.filesList.push(event.target.files[i]);
      }
    },

    // 取消上传的图片
    removeUpImg(suoyin) {
      let me = this;

      me.filesList.splice(suoyin, 1);
    },
    //表单提交
    xinjian() {
      let me = this;
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
        timeout: 20000
      };
      let url = "/notice/manage/add";
      for (let i in this.right.list) {
        var map = this.right.list[i];
        let json = {
          userId: map.userId,
          userName: map.userName,
          userDeptId: map.deptId,
          userDeptName: map.deptName,
          deptOrgId: map.unitId,
          deptOrgName: map.unitName
        };
        this.form.noticeUsers.push(json);
      }
      if (!me.form.title) {
        this.hw_warn("请填写通知标题！");
        return false;
      }
      if (me.error) {
        this.hw_warn("通知标题不得超过100个字！");
        return false;
      }
      if (!me.form.typeId) {
        this.hw_warn("请选择通知类型！");
        return false;
      }
      if (!me.form.noticeImportance) {
        this.hw_warn("请选择文件重要性！");
        return false;
      }
      if (this.form.noticeUsers.length == 0) {
        this.hw_warn("请选择接收人员！");
        return false;
      }
      var size = 0;
      for (var i in me.filesList) {
        size += me.filesList[i].size / 1024 / 1024;
      }
      if (size >= 100) {
        this.hw_warn("文件大小不得大于100M！");
        return false;
      }
      this.submitflag = true;
      let forms = new FormData();
      let bean = {};
      bean.title = me.form.title;
      bean.typeId = me.form.typeId;
      bean.noticeImportance = me.form.noticeImportance;
      bean.noticeUsers = me.form.noticeUsers;
      bean.content = me.form.content;

      forms.append("noticeBean", JSON.stringify(bean));

      for (let i in me.filesList) {
        let file = me.filesList[i];
        forms.append("files", file);
      }
      me.$ajax
        .post(url, forms, config)
        .then(out => {
          this.submitflag = false;
          me.hw_result(out.data, true, me, () => {
            if (out.data.code == "S0000") {
              me.hw_success("发布成功");
              var that = this;
              setTimeout(function() {
                that.$router.push({ name: "outbox" });
              }, 1000);
            }
          });
        })
        .catch(error => {
          console.log(error);
          this.submitflag = false;
          me.hw_error("请求超时,请稍后再试！");
        });
    },

    backPage() {
      //返回上一页
      this.$router.back(-1);
    }
  }
};
</script>

<style>
.newNotice .textearMesBox {
  height: 200px;
  margin: 0 0 60px;
}
.newNotice .textearMesBox .ql-formats span {
  line-height: normal;
}
@media screen and (max-width: 1310px) {
  .newNotice .textearMesBox {
    margin: 0 0 98px;
  }
}
</style>
